﻿using RndMaterialDisposalService.Attrbutes;
using System.Reflection;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class AutoInjectExtension
    {
        /// <summary>
        /// 根据NAutowiredAttribute特性自动注入Service
        /// </summary>
        /// <param name="builder"></param>
        public static void AddAutoInject(this IServiceCollection builder)
        {
            var types = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.GetCustomAttribute<NAutowiredAttribute>() != null);
            foreach (var item in types)
            {
                var nautowired = item.GetCustomAttribute<NAutowiredAttribute>();
                var lifecycle = nautowired!.Lifecycle;
                var interfaceClass = nautowired.InterfaceType == null ? item.GetInterfaces().FirstOrDefault() : nautowired.InterfaceType;

                if (lifecycle == Lifecycle.Singleton)
                {
                    builder.AddSingleton(interfaceClass!, item);
                }
                else if (lifecycle == Lifecycle.Transient)
                {
                    builder.AddTransient(interfaceClass!, item);
                }
                else if (lifecycle == Lifecycle.Scoped)
                {
                    builder.AddScoped(interfaceClass!, item);
                }
            }
        }
    }
}
